package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Title:
 * Author: fusu
 * DateTime:  2023/3/25
 * Description:
 **/
@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;

    /**
     * @return com.goods.common.vo.system.PageVO
     * @Author: fusu
     * @Description: 入库记录列表展示
     * @DateTime:9:33 2023/3/25
     * @params: [pageNum, pageSize, inStockVO]
     */
    @Override
    public PageVO findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {
        PageHelper.startPage(pageNum, pageSize);
        List<InStockVO> inStockList = inStockMapper.findInStockList(inStockVO);
        PageInfo<InStockVO> info = new PageInfo<>(inStockList);
        long total = info.getTotal();
        return new PageVO(total, inStockList);
    }

    /**
     * @return void
     * @Author: fusu
     * @Description: 入库记录添加
     * @DateTime:15:31 2023/3/25
     * @params: [inStockVO]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addIntoStock(InStockVO inStockVO) {
        InStock inStock = new InStock();
        BeanUtils.copyProperties(inStockVO, inStock);
        if (inStockVO.getSupplierId() == null) {
            //新增物资来源记录
            Supplier supplier = new Supplier();
            BeanUtils.copyProperties(inStockVO, supplier);
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            int insert = supplierMapper.insert(supplier);
            inStock.setSupplierId(supplier.getId());
        }
        String inNum = "FUSU:" + UUID.randomUUID().toString().replaceAll("-", "");
        inStock.setInNum(inNum);
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        inStock.setOperator("admin");
        inStock.setStatus(2);
        List<Map<String, Object>> products = inStockVO.getProducts();
        Integer allProductNumber = 0;
        for (Map<String, Object> map : products) {
            Integer productId = (Integer) map.get("productId");
            Integer productNumber = (Integer) map.get("productNumber");
            InStockInfo inStockInfo = new InStockInfo();
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setModifiedTime(new Date());
            inStockInfo.setInNum(inStock.getInNum());
            inStockInfo.setPNum(productMapper.selectByPrimaryKey(productId).getPNum());
            inStockInfo.setProductNumber(productNumber);
            //一条入库记录对应多条商品
            inStockInfoMapper.insert(inStockInfo);
            allProductNumber += productNumber;
        }
        inStock.setProductNumber(allProductNumber);
        inStockMapper.insert(inStock);

        //根据productId获取product
//        if (productId != null) {
//            Product product = productMapper.selectByPrimaryKey(productId);
//            Example example = new Example(ProductStock.class);
//            Example.Criteria criteria = example.createCriteria();
//            criteria.andEqualTo("pNum", product.getPNum());
//            ProductStock productStock = productStockMapper.selectOneByExample(criteria);
//            if (productStock != null) {
//                //添加库存数量
//                productStock.setStock(productStock.getStock() + productNumber);
//                productStockMapper.updateByPrimaryKey(productStock);
//            } else {
//                //新增记录
//                productStock = new ProductStock();
//                productStock.setStock(productNumber.longValue());
//                productStock.setPNum(product.getPNum());
//                productStockMapper.insert(productStock);
//            }
//        }
    }

    /**
     * @return com.goods.common.vo.business.InStockDetailVO
     * @Author: fusu
     * @Description: 入库记录明细
     * @DateTime:8:44 2023/3/27
     * @params: [inStockId]
     */
    @Override
    public InStockDetailVO getInStockDetail(Long inStockId) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        //1.查出入库记录
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        BeanUtils.copyProperties(inStock, inStockDetailVO);
        inStockDetailVO.setTotal(inStock.getProductNumber());
        //2.根据supplierId查出supplier物资来源
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier, supplierVO);
        //3.根据inNum查出inStockInfo入库明细
        Example example = new Example(InStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inNum", inStock.getInNum());
        List<InStockInfo> inStockInfos = inStockInfoMapper.selectByExample(example);
        List<InStockItemVO> inStockItemVOS = inStockInfos.stream().map(inStockInfo -> {
            InStockItemVO inStockItemVO = new InStockItemVO();
            inStockItemVO.setCount(inStockInfo.getProductNumber());
            Example productExample = new Example(Product.class);
            Example.Criteria o = productExample.createCriteria();
            o.andEqualTo("pNum", inStockInfo.getPNum());
            Product product = productMapper.selectOneByExample(productExample);
            BeanUtils.copyProperties(product, inStockItemVO);
            return inStockItemVO;
        }).collect(Collectors.toList());
        inStockDetailVO.setSupplierVO(supplierVO);
        inStockDetailVO.setItemVOS(inStockItemVOS);
        return inStockDetailVO;
    }

    /**
     * @return void
     * @Author: fusu
     * @Description: 通过审核入库
     * @DateTime:9:23 2023/3/27
     * @params: [inStockId]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishInStock(Long inStockId) {
        //1.添加库存信息
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        if (inStock != null) {
            String inNum = inStock.getInNum();
            Example example = new Example(InStockInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("inNum", inStock.getInNum());
            List<InStockInfo> inStockInfos = inStockInfoMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(inStockInfos)) {
                //根据入库记录更新库存信息
                inStockInfos.stream().forEach(inStockInfo -> {
                    String pNum = inStockInfo.getPNum();
                    Example psExample = new Example(ProductStock.class);
                    Example.Criteria psCriteria = psExample.createCriteria();
                    psCriteria.andEqualTo("pNum", pNum);
                    //根据pNum获取物资库存
                    ProductStock productStock = productStockMapper.selectOneByExample(psExample);
                    if (productStock != null) {
                        productStock.setStock(productStock.getStock() + inStockInfo.getProductNumber());
                        productStockMapper.updateByPrimaryKey(productStock);
                    } else {
                        productStock = new ProductStock();
                        productStock.setPNum(pNum);
                        productStock.setStock(inStockInfo.getProductNumber().longValue());
                        productStockMapper.insert(productStock);
                    }
                });
            }
            //2.添加库存成功后修改状态
            inStock.setStatus(0);
            inStockMapper.updateByPrimaryKey(inStock);
        }

    }

    /**
     * @return void
     * @Author: fusu
     * @Description: 加入回收站
     * @DateTime:10:36 2023/3/27
     * @params: [inStockId]
     */
    @Override
    public void removeByInStockId(Long inStockId) {
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        if (inStock != null) {
            inStock.setStatus(1);
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }

    /**
     * @return void
     * @Author: fusu
     * @Description: 删除入库记录
     * @DateTime:10:45 2023/3/27
     * @params: [inStockId]
     */
    @Override
    public void deleteByInstockId(Long inStockId) {
        inStockMapper.deleteByPrimaryKey(inStockId);
    }

    /**
     * @return void
     * @Author: fusu
     * @Description: 还原入库记录
     * @DateTime:14:09 2023/3/27
     * @params: [inStockId]
     */
    @Override
    public void backByInStockId(Long inStockId) {
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        if (inStock != null) {
            inStock.setStatus(0);
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }
}
